import React from 'react';
import * as PropTypes from 'prop-types';

import { List, Calendar } from 'antd-mobile';
import moment from 'moment'

const now = new Date();

class myCalendar extends React.Component {
  static defaultProps = {
    format: 'YYYY/MM/DD',
  }

  originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;

  constructor(props) {
    super(props);

    let value;
    if ('defaultValue' in props) {
      value = props.defaultValue;
    }
    this.state = {
      value,
      show: false,
    };
  }

  /**
   * 选择时间
   */
  onConfirm = (startTime, endTime) => {
    const lastValue = this.state.value;
    document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
    this.setState({
      show: false,
    });

    const value = [startTime, endTime]
    const { onChange } = this.props
    if (onChange && value !== lastValue) {
      this.setState({
        value,
      })
      onChange(value)
    }
  }

  onCancel = () => {
    document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
    this.setState({
      show: false
    });
  }

  renderExtra = (value) => {
    const { format } = this.props;
    const startTime = moment(value[0]).format(format)
    const endTime = moment(value[1]).format(format)
    return (<>{`${startTime}-${endTime}`}</>)
  }

  render = () => {
    const { value } = this.state;

    const extra = this.renderExtra(value)
    return (<div>
      <List>
        <List.Item arrow="horizontal" className={'custom-calendar'}
          onClick={() => {
            document.getElementsByTagName('body')[0].style.overflowY = 'hidden';
            this.setState({
              show: true
            });
          }}
          extra={extra}
        >
          选择时间：
        </List.Item>
      </List>
      <Calendar
        defaultValue={value}
        maxDate={new Date(now)}
        visible={this.state.show}
        showShortcut={true}
        onCancel={this.onCancel}
        onConfirm={this.onConfirm}
      />
    </div>);
  }

}

myCalendar.propTypes = {
  onChange: PropTypes.func,
}
export default myCalendar;
